﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using System.Collections.Immutable;
using System.Composition;

namespace AiMoCodeCompletion
{
    [Export]
    [ExportCompletionProvider("CusomizedCompletionProvider", LanguageNames.CSharp)]
    public class CusomizedCompletionProvider : CompletionProvider
    {
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (context.Trigger.Character != '#' && context.Trigger.Character != 'r')
            {
                return;
            }
            var document = context.Document;
            var position = context.Position;
            var cancellationToken = context.CancellationToken;
            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            if (syntaxTree == null) return;
            var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            var token = root.FindToken(position);
            string text = token.LeadingTrivia.ToFullString().TrimEnd();

            // 检查前一个字符是否是 '#'
            if (token.IsKind(SyntaxKind.UsingKeyword) && (text.EndsWith('#') || text.EndsWith("#r")))
            {
                // 添加 #r 的补全项
                context.AddItem(GetCustomCompletionItem());
            }
        }
        public CompletionItem GetCustomCompletionItem()
        {
            // 定义显示文本
            string displayText = "r";

            // 定义过滤文本
            string filterText = "r ";

            // 定义排序文本
            string sortText = "001";

            // 定义属性字典
            //var properties = ImmutableDictionary<string, string>.Empty
            //    .Add("DescriptionProperty", "Text|r 关键字");

            // 定义标签数组
            var tags = ImmutableArray.Create("Keyword", "Custom");// Microsoft.CodeAnalysis.Glyph.Keyword

            // 定义补全项规则
            //var rules = CompletionItemRules.Default;

            // 创建 CompletionItem
            var completionItem = CompletionItem.Create(
                displayText: displayText,
                filterText: filterText,
                sortText: sortText,
                //properties: properties,
                tags: tags
                );

            return completionItem;
        }
    }
}
